import { Map, TileLayer, VectorLayer } from 'maptalks'
import { feature, featureCollection, geometry, bbox, intersect, union, isolines, point } from "@turf/turf";
import { interpolate } from './rewrite/turfinterpolate';

const gridFeatureCollection = function (grid) {
  var i, j, x, y, z
  var n = grid.data.length // 列数
  var m = grid.data[0].length // 行数
  var pointArray = []
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      x = i * grid.width + grid.xlim[0]
      y = j * grid.width + grid.ylim[0]
      z = grid.data[i][j]
      pointArray.push(point([x, y], { value: z }))
    }
  }
  return pointArray
}

let map = new Map('map', {

  zoom: 5,
  center: [114, 30],
  baseLayer: new TileLayer('base', {
    urlTemplate: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
  })
})

const options = {
  cellSize: 0.1,
  weight: 4,
  units: 'degrees',
  zProperty: 'value'
}

let breaks = [-0.8, -0.4, 0, 0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 50]
breaks = [-0.8, 0.998, 0.9984, 0.9988, 0.9992, 0.9996, 1, 1.0004, 1.0008, 1.0012, 1.0016, 1.002, 2,];

// breaks = [1.0003, 1.0004, 1.0005, 1.0006, 1.0007, 1.0008, 1.0009, 1.0010, 1.0011, 1.0012, 1.0013, 1.0014, 1.005]


let colorList = [
  '#F03100',
  '#F03100',
  '#F09511',
  '#F0C70A',
  '#B7E000',
  '#11F70C',
  '#00F099',
  '#00F099',
  '#11F70C',
  '#B7E000',
  '#F0C70A',
  '#F09511',
  '#F03100',
  '#F03100',
]


colorList = [
  "#F03100",
  "#F09511",
  "#F0C70A",
  "#B7E000",
  "#11F70C",
  "#00F099",
  "#00F099",
  "#11F70C",
  "#B7E000",
  "#F0C70A",
  "#F09511",
  "#F03100",
];




let feaCol = undefined


let index = 0
// let interval = setInterval(() => {
//   map.removeLayer('idw')
//   map.removeLayer('grid')
//   map.removeLayer('idwline')
//   let sampleData = sampleData1226[index]
//   idw(sampleData)
//   index++
//   if (index === sampleData1226.length) {
//     clearInterval(interval)
//     alert('game over')
//   }
// }, 2000);

// let sampleData = sampleData1226[17]
// let pointArray = sampleData.filter((ii) => ii.lat && ii.lon && ii.value && (ii.value > 0 && ii.value < 5))
// let idwData = pointArray.map((i) => {
//   return [i.lon, i.lat, Number(i.value)]
// })

const idw = function (idwData, boundary) {


  if (Array.isArray(idwData)) {
    feaCol = featureCollection(idwData.map(i => {
      const geo = {
        "type": "Point",

        "coordinates": [i[0], i[1]]
      };
      const fea = feature(geo)

      fea.properties[options.zProperty] = i[2] * 1

      return fea
    }))
  }


  // k

  var values = [], lons = [], lats = [];
  for (var i = 0; i < idwData.length; i++) {
    var item = idwData[i];
    values.push(item[2]);
    lons.push(item[0]);
    lats.push(item[1]);
  }

  const ex = bbox(boundary)

  // 根据边界信息添加矩形坐标
  const polygons = [[[ex[0], ex[1]], [ex[0], ex[3]], [ex[2], ex[3]], [ex[2], ex[1]]]]




  const grid = interpolate(feaCol, options.cellSize, {
    gridType: 'point',
    property: options.zProperty,
    units: options.units,
    weight: options.weight,
    bbox: bbox(boundary)
  })

  grid.features.map(i => {
    let val = i.properties['value']
    i.properties['value'] = (val * 1).toFixed(4)
    return i
  })


  const gridLayer = new VectorLayer('grid').addTo(map)
  gridLayer.addGeometry(grid)
  gridLayer.setStyle({
    symbol: {
      textName: '{value}',
      textSize: 12
    }
  })
  gridLayer.setZIndex(50)

  const isobandsRes = turf.isobands(grid, breaks, {
    zProperty: options.zProperty
  })

  // 处理边界数据
  const geoType = boundary.type
  switch (geoType) {
    case 'FeatureCollection':
      let unionFea = boundary.features[0]
      for (let index = 1; index < boundary.features.length; index++) {
        const fea = boundary.features[index];
        unionFea = union(unionFea, fea)
      }

      boundary = unionFea
      break
    case 'Feature':
      break
    default:
      throw new Error('无效的边界数据')
  }


  // const intersectRes = []
  // const z = options.zProperty
  // isobandsRes.features.forEach((isoFea) => {
  //   const pro = {}
  //   if (isoFea.properties && isoFea.properties[z] && isoFea.geometry.coordinates.length > 0) {// 校验插值后iso结果
  //     const intersection = intersect(isoFea, boundary)
  //     if (intersection) {
  //       intersection.properties[z] = isoFea.properties[z]
  //       intersectRes.push(intersection)
  //     }
  //   }
  // })


  const idwLayer = new VectorLayer('idw').addTo(map)

  idwLayer.addGeometry(isobandsRes)










  const stops = []
  for (let index = 0; index < breaks.length - 1; index++) {
    stops.push([`${breaks[index]}-${breaks[index + 1]}`, `${colorList[index]}`])
  }

  idwLayer.setStyle({
    symbol: {
      polygonFill: {
        type: 'categorical',
        property: 'value',
        stops: stops,
        default: 'black'
      },
      lineColor: {
        type: 'categorical',
        property: 'value',
        stops: stops,
        default: 'black'
      },
      lineWdith: 1,
    }
  })

  // line
  let isolinesRes = isolines(grid, breaks, {
    zProperty: options.zProperty
  })


  const lineLayer = new VectorLayer('idwline', isolinesRes).addTo(map)
  // idwLayer.hide()
  gridLayer.hide()
  lineLayer.hide()
}

let pointArray = sampleData1226[17].filter((ii) => ii.lat && ii.lon && ii.value && (ii.value > 0 && ii.value < 5))
let idwData = pointArray.map((i) => {
  return [i.lon, i.lat, Number(i.value)]
})
idw(idwData, huabei)



